package com.sanq.product.mcgs.controller;

import com.google.common.collect.Lists;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.string.DigestUtil;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.mcgs.common.Redis;
import com.sanq.product.mcgs.entity.MemberParam;
import com.sanq.product.mcgs.entity.vo.MemberVo;
import com.sanq.product.mcgs.filter.SecurityFilter;
import com.sanq.product.mcgs.service.MemberService;
import com.sanq.product.mcgs.service.PermissionService;
import com.sanq.product.mcgs.util.PwdUtil;
import com.sanq.product.mcgs.util.RequestUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.security.annotation.IgnoreSecurity;
import com.sanq.product.security.annotation.Security;
import com.sanq.product.security.enums.TokenTime;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/member")
public class MemberController {

    @Resource
    private MemberService memberService;
    @Resource
    private JedisPoolService jedisPoolService;
    @Resource
    private PermissionService permissionService;

    @LogAnnotation(description = "通过ID得到详情")
    @GetMapping(value = "/get/{id}")
    public Response getById(HttpServletRequest request, @PathVariable("id") Integer id) {
        MemberVo memberVo = memberService.findById(id);

        return memberVo != null ? new Response().success(memberVo) : new Response().failure();
    }

    @LogAnnotation(description = "删除数据")
    @DeleteMapping(value = "/delete")
    public Response deleteById(HttpServletRequest request, @RequestBody MemberVo memberVo) {

        int result = memberService.delete(memberVo);
        return result == 1 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "分页查询数据")
    @GetMapping(value = "/list")
    public Response findListByPager(HttpServletRequest request, MemberVo memberVo, Pagination pagination) {

        Pager<MemberVo> pager = memberService.findListByPage(memberVo, pagination);

        return pager != null ? new Response().success(pager) : new Response().failure();
    }

    @LogAnnotation(description = "查询所有数据")
    @GetMapping(value = "/all")
    public Response findList(HttpServletRequest request, MemberVo memberVo) {

        List<MemberVo> list = memberService.findList(memberVo);
        return list != null ? new Response().success(list) : new Response().failure();
    }

    @LogAnnotation(description = "添加数据")
    @PostMapping(value = "/save")
    public Response add(HttpServletRequest request, @Valid @RequestBody MemberParam param) {

        MemberVo memberVo = new MemberVo();
        memberVo.setEmail(param.getEmail());
        List<MemberVo> list = memberService.findList(memberVo);

        if (list != null && !list.isEmpty())
            return new Response().failure(String.format("账号%s已存在", param.getEmail()));

        BeanUtils.copyProperties(param, memberVo);

        memberVo.setLoginName(memberVo.getEmail());
        memberVo.setLoginPwd(PwdUtil.getPwd(DigestUtil.getInstance().md5(memberVo.getLoginName()), memberVo.getLoginName()));

        int result = memberService.save(memberVo);

        return result == 1 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "通过ID修改数据")
    @PutMapping(value = "/update/{id}")
    public Response updateByKey(HttpServletRequest request,
                                @Valid @RequestBody MemberParam param,
                                @PathVariable("id") Integer id) {

        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(param, memberVo);

        int result = memberService.update(memberVo, id);

        return result == 1 ? new Response().success() : new Response().failure();
    }

    @Security
    @LogAnnotation(description = "登录")
    @PostMapping(value = "/login")
    public Response login(HttpServletRequest request, @RequestBody MemberVo memberVo) {

        if (StringUtil.isEmpty(memberVo.getLoginName()))
            return new Response().failure("登录账号不能为空");

        if (StringUtil.isEmpty(memberVo.getLoginPwd()))
            return new Response().failure("密码不能为空");

        memberVo.setLoginPwd(PwdUtil.getPwd(memberVo.getLoginPwd(), memberVo.getLoginName()));

        MemberVo result = memberService.login(memberVo);

        if (result == null)
            return new Response().failure("登录失败, 请检查用户名和密码");

        if (result.getUserStatus() == 0)
            return new Response().failure("当前账号已锁定， 请联系管理员");

        String token = DigestUtil.getInstance().md5(result.getLoginName() + "::" + result.getLoginPwd());

        result.setLoginPwd("");
        jedisPoolService.set(Redis.ReplaceKey.getMemberTokenKey(token), JsonUtil.obj2Json(result), TokenTime.TOKEN_TIME.getTime());

        //得到当前的button权限
        permissionService.findPermissionUrlByMemberId(result.getId());

        return new Response().success(token);
    }

    @LogAnnotation(description = "通过Token获取用户")
    @GetMapping(value = "/getInfoByToken")
    public Response getInfoByToken(HttpServletRequest request) {

        return new Response().success(RequestUtil.get());
    }

    @LogAnnotation(description = "修改密码")
    @PutMapping(value = "/updatePwd")
    public Response updatePwd(HttpServletRequest request, @RequestBody Map<String, String> map) {

        MemberVo memberVo = RequestUtil.get();

        String newPwd = map.get("newLoginPwd");
        String confirmPwd = map.get("confirmPwd");

        if (StringUtil.isEmpty(newPwd))
            return new Response().failure("新密码不能为空");

        if (StringUtil.isEmpty(confirmPwd))
            return new Response().failure("确认密码不能为空");

        if (!newPwd.equals(confirmPwd))
            return new Response().failure("确认密码和新密码不一致");

        MemberVo params = new MemberVo();
        params.setLoginPwd(PwdUtil.getPwd(newPwd, memberVo.getLoginName()));

        memberService.update(params, memberVo.getId());

        return new Response().success();
    }
}